//
//  RootController.m
//  CenturyCity
//
//  Created by nsm on 2019/7/24.
//  Copyright © 2019 beisheng. All rights reserved.
//

#import "RootController.h"

static const CGFloat kHomeIconW = 36;
static const CGFloat kNormalIconW = 24;
static const CGFloat kNormalSpacing = 1;

@interface RootTabBarButton : NSMButton
@property (nonatomic) BOOL isHome;
@end

@implementation RootTabBarButton
- (void)setSelected:(BOOL)selected {
    if (_isHome) {
        CGFloat imageW = selected? kHomeIconW: kNormalIconW;
        CGFloat spacing = selected? 0: kNormalSpacing;
        self.imageSize = CGSizeMake(imageW, imageW);
        self.spacing = spacing;
        
        NSString *title = selected? nil: @"首页";
        // 这个会触发setNeedsLayout
        self.title = title;
    } else {
        self.imageSize = CGSizeMake(kNormalIconW, kNormalIconW);
        self.spacing = kNormalSpacing;
    }
    
    [super setSelected:selected];
}
@end


@interface RootTabBarView : UIView
@property(nonatomic) NSUInteger selectedIndex; // 这个只改变状态,不触发事件
@property (nonatomic, weak) NSMButton *selectedBtn;
@property (nonatomic, strong) NSArray<RootTabBarButton *> *tabBarBtns;
@property (nonatomic, copy) void(^didSelectedAtIndex)(NSInteger idx, BOOL needLogin);
- (void)reloadTabBarItems:(NSArray *)items selectedIndex:(NSUInteger)selectedIndex;
@end

@implementation RootTabBarView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

- (void)reloadTabBarItems:(NSArray *)items selectedIndex:(NSUInteger)selectedIndex {
    CGFloat w = self.width / items.count;
    CGFloat h = self.height;
    
    NSMutableArray<RootTabBarButton *> *btns = @[].mutableCopy;
    @nsm_weak(self)
    for (int i=0; i<items.count; i++) {
        NSDictionary *item = items[i];
        NSString *image_n = FormatString(@"tabbar_%02d_n", i+1);
        NSString *image_s = FormatString(@"tabbar_%02d_s", i+1);

        RootTabBarButton *btn = RootTabBarButton.new;
        btn.left = w * i;
        btn.size = CGSizeMake(w, h);
        btn.adjustsWhenHighlighted = NO;
        btn.imagePosition = NSMButtonImagePositionTop;
        btn.titleLabel.font = CustomFont(12);
        [btn setTitleColor:COLOR_0 forState:UIControlStateNormal];
        [btn setTitleColor:THEME_COLOR forState:UIControlStateSelected];
        [btn setImage:NameImage(image_n) forState:UIControlStateNormal];
        [btn setImage:NameImage(image_s) forState:UIControlStateSelected];
        btn.title = item[@"barTitle"];
        [self addSubview:btn];
        [btns addObject:btn];
        
        if (i==selectedIndex) {
            // 默认选中
            btn.selected = YES;
            _selectedBtn = btn;
            _selectedIndex = i;
        } else
            btn.selected = NO;

        [btn addBlockForControlEvents:UIControlEventTouchUpInside block:^(NSMButton *sender) {
            @nsm_strong(self)
            // 防止重复点击
            if (sender.selected) return;
            
            // MARK:根据业务需要判断登录的下标(需要拦截按钮选中状态)
            BOOL needLogin = NO;
            if (!needLogin) {
                self.selectedBtn.selected = NO;
                sender.selected = YES;
                self.selectedBtn = sender;
                self.selectedIndex = i;
            }
            !self.didSelectedAtIndex?:self.didSelectedAtIndex(i, needLogin);
        }];
    }
    _tabBarBtns = btns;
    
    UIView *line = UIView.new;
    line.size = CGSizeMake(self.width, kSinglePixel);
    line.backgroundColor = SEPARATOR_COLOR;
    [self addSubview:line];
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    if (_selectedIndex == selectedIndex) return;
    if (selectedIndex >= _tabBarBtns.count) return;
    
    NSMButton *sender = _tabBarBtns[selectedIndex];
    _selectedBtn.selected = NO;
    sender.selected = YES;
    _selectedBtn = sender;
    _selectedIndex = selectedIndex;
}

@end

@interface RootTabBar : UITabBar
@property (nonatomic, strong) RootTabBarView *barView;
@property (nonatomic, copy) void(^onClickCenter)(NSMButton *btn);
@end

@implementation RootTabBar
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self didInitialize];
    }
    return self;
}

- (void)didInitialize {
    // 禁止旋转的
    CGRect frame = CGRectMake(0, 0, kScreenWidth, 49);
    RootTabBarView *barView = [[RootTabBarView alloc] initWithFrame:frame];
    [self addSubview:barView];
    self.barView = barView;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    for (UIView *view in self.subviews) {
        if (view != self.barView) {
            view.hidden = YES;
        }
    }
}
@end

@interface RootController ()
@property (nonatomic, strong) NSArray *controllers;
@end

@implementation RootController

#pragma mark - lifeCycle
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

#pragma mark - override
- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    // 临时copy一份
    NSUInteger idx = selectedIndex;
    BOOL hasMore = self.controllers.count > 5;
    if (hasMore) {
        if (selectedIndex > 3) {
            // 保留前4个
            NSMutableArray *vcs = [self.controllers subarrayWithRange:NSMakeRange(0, 4)].mutableCopy;
            [vcs addObject:self.controllers[idx]];
            
            self.viewControllers = @[UIViewController.new];
            selectedIndex = 4;
            self.viewControllers = vcs;
        }
    }
    
    [super setSelectedIndex:selectedIndex];
        
    // 初始化的时候是系统的UITabbar
    if (![self.tabBar isKindOfClass:RootTabBar.class]) return;
    
    RootTabBar *tabBar = (RootTabBar *)self.tabBar;
    tabBar.barView.selectedIndex = idx;
}

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *array = @[@{@"clsName": @"TextFieldController",
                         @"barTitle": @"首页",
                         @"navTitle": @"",
                         @"image": @"tabbar_01"},
                       @{@"clsName": @"TextFieldController",
                         @"barTitle": @"生活圈",
                         @"navTitle": @"",
                         @"image": @"tabbar_02"},
                       @{@"clsName": @"TextFieldController",
                         @"barTitle": @"外卖/配送",
                         @"navTitle": @"",
                         @"image": @"tabbar_03"},
                       @{@"clsName": @"TextFieldController",
                         @"barTitle": @"我的",
                         @"navTitle": @"",
                         @"image": @"tabbar_04"},
                       @{@"clsName": @"ZRLController",
                         @"barTitle": @"卧槽",
                         @"navTitle": @"",
                         @"image": @"tabbar_05"},
                       @{@"clsName": @"DelegatesController",
                         @"barTitle": @"第六个",
                         @"navTitle": @"",
                         @"image": @"tabbar_06"}];
    [self initChildControllers:array];
    
    RootTabBar *tabBar = RootTabBar.new;
    tabBar.backgroundColor = COLOR_4;
    [tabBar.barView reloadTabBarItems:array selectedIndex:0];
    [self setValue:tabBar forKey:@"tabBar"];
    
    @nsm_weak(self)
    tabBar.barView.didSelectedAtIndex = ^(NSInteger idx, BOOL needLogin) {
        @nsm_strong(self)
        if (needLogin)
            [self loginWithSuccess:^{}];
        else {
             self.selectedIndex = idx;
        }
    };
}

- (void)initChildControllers:(NSArray *)array {
    NSMutableArray *arrayM = @[].mutableCopy;
    for (NSDictionary *dic in array) {
        [arrayM addObject:[self controller:dic]];
    }
    self.controllers = arrayM;
    self.viewControllers = arrayM;
}

- (UIViewController *)controller:(NSDictionary *)dic {
    NSString *className = dic[@"clsName"];
    UIViewController *vc = [NSClassFromString(className) new];
    if (!vc) vc = [UIViewController new];
    vc.title = dic[@"navTitle"];
    return [NSMNavigationController controller:vc];
}

#pragma mark - setter/getter

#pragma mark - network

#pragma mark - method/public
- (void)loginWithSuccess:(void (^)(void))success {
    [self presentLoginController:^(LoginController *vc) {
        vc.didLoginSuccess = ^(id data) {
            !success?:success();
        };
    } animated:YES completion:nil];
}

#pragma mark - method/private

#pragma mark - action

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
